<template>
  <div class="user-manage-wrapper">
    <el-row class="user-row" type="flex" :gutter="10">
      <el-col class="user-col" :xs="9" :sm="8" :md="7" :lg="5" :xl="6" v-if="userManageOrg">
        <el-card class="box-card">
          <div class="card-header-box" slot="header">
            <span class="box-card-title">组织机构</span>
          </div>
          <tree-view ref="first" :treeData="generateTree" :expandOnClickNode="false" :highlightCurrent="highlightCurrent" @on-handle-click="treeClick"></tree-view>
        </el-card>
      </el-col>
      <el-col class="user-col" :xs="elCol.xs" :sm="elCol.sm" :md="elCol.md" :lg="elCol.lg" :xl="elCol.xl">
        <table-view class="user-table"
          :cols="cols"
          :tableData="tableData"
          :canCheck="true"
          :showIndex="true"
          :showSearch="true"
          :searchCondition="searchCondition"
          :showOperate="true"
          :showPaginator="true"
          :buttonCount="2"
          :clearSelect="clearSelect"
          :pageNumber="pageNumber"
          :pageSize="pageSize"
          :totalRecords="totalRecords"
          :operateButtons="operateButtons"
          @on-operate="clickOperate"
          @on-search="search"
          @selection-change="selectChange"
          @size-change="sizeChange"
          @current-page-change="pageChange"
          @preClick="pageChange"
          @nextClick="pageChange"
        >
          <div class="operate-button-group">
            <el-button size="mini" type="primary" icon="el-icon-plus" @click="showModal('add')">新增</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="showModal('delete')">删除</el-button>
          </div>
        </table-view>
      </el-col>
    </el-row>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="540px">
      <div class="dialog-container" v-if="dialogTitle === '删除'">您确定要删除这些信息吗？</div>
      <div class="dialog-container" v-else-if="dialogTitle === '重置密码'">
        重置密码后用户的旧密码将不能使用，您确定要重置该用户的密码吗？
      </div>
      <div class="dialog-container" v-else-if="dialogTitle === '修改密码'">
        <input-list-view :items="editPwdItems" labelWidth="100px" width="500px"></input-list-view>
      </div>
      <div class="dialog-container" v-else>
        <input-list-view :items="dialogItems" :isCascaderShowAll="false" labelWidth="140px" width="500px"></input-list-view>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="save(dialogTitle)" v-if="showSaveButton">保存</el-button>
        <el-button type="primary" size="small" @click="confirm(dialogTitle)" v-if="!showSaveButton">确定</el-button>
        <el-button size="small" @click="dialogVisible = false" v-show="dialogTitle === '修改密码'">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "user-manage",
    data() {
      let baseUrl = managerRemoteUrl;
      return {
        urls: {
          // getHeaderUrl: "./static/json/user-manage-header.json",
          getHeaderUrl: baseUrl + "/user/header",//表头
          getTableDataUrl: baseUrl + "/user", //用户列表
          getUserRoleUrl: baseUrl + "/combobox/role", //用户角色
          getOrgTreeUrl: baseUrl + "/combobox/org/tree", //组织机构树
          addUrl: baseUrl + "/user/data", //新增和编辑
          deleteUrl: baseUrl + "/user/del", //删除
          editPwdUrl: baseUrl + "/user/pwd", //修改密码

          resetPwdUrl: baseUrl + "/reset/password", //重置密码
        },
        cols: [],
        tableData: [],
        selectedData: [],
        clearSelect: false,
        searchCondition: [],
        pageNumber: 1,
        pageSize: 10,
        totalRecords: 0,
        dialogTitle: "",
        dialogVisible: false,
        showSaveButton: true,
        dialogItems: [],
        operateButtons: ['编辑', '修改密码'],
        currentRow: null,
        userInfo: {},
        editPwdItems: [
          {type: 'password', field: 'oldPwd', label: '旧密码',value:"", rule: {required: true}},
          {type: 'password', field: 'newPwd', label: '新密码',value:"", rule: {required: true}}
        ],
        value: {},
        searchFilter: {}, // 搜索
        orgItems:null,
        generateTree: [],
        orgId:"",
        highlightCurrent:true,
        userManageOrg:userManageOrg,
        elCol:{xs:15, sm:16, md:17, lg:19, xl:18},
      };
    },
    mounted() {
      this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      if(!userManageOrg){
        for (let key in this.elCol){
          this.elCol[key] = 24;
        }
      }
      this.getInitData();
      this.getTableData();
    },
    methods: {
      //获取表头数据
      getHeader() {
        this.cols = [];
        return new Promise((resolve, reject) => {
          this.httpRequest("get", this.urls.getHeaderUrl, {}, {
            fullSuccess: true
          }).then(res => {
            this.cols = res.value.cols;
            this.searchCondition = [];
            res.value.cols.forEach(d => {
              if (d.search) {
                let obj = this.cloneObj(d);
                obj["label"] = d.header;
                obj["value"] = null;
                this.searchCondition.push(obj);
              }
            });
            // this.searchFilter = this.setFilter(this.searchCondition);
            resolve(res.value)
          })
        })
      },
      //获取全部角色
      getUserRole() {
        return new Promise((resolve, reject) => {
          this.httpRequest("get", this.urls.getUserRoleUrl, {}, {
            fullSuccess: true
          }).then(res => {
            resolve(res.value)
          })
        })
      },
      //获取组织机构
      getOrgTree() {
        return new Promise((resolve, reject) => {
          this.httpRequest("get", this.urls.getOrgTreeUrl, {}, {
            fullSuccess: true
          }).then(res => {
            if (res.value.children && res.value.children.length != 0) {
              this.generateTree = res.value.children;
            }
            resolve(res.value)
          })
        })
      },
      getInitData() {
        Promise.all([this.getHeader(), this.getUserRole(),this.getOrgTree()]).then(res => {
          this.cols.forEach(d => {
            if (d.field === "user_role_edit") {
              d.option = res[1];
            }else if (d.field === "user_org_edit") {
              d.option = this.initChildren([this.cloneObj(res[2])],null);
              this.orgItems = d.option;
            }
          });
        })
      },
      //将children为空数组的设置为null
      initChildren(arr,value) {
        return arr.map(d=> {
          let obj = this.cloneObj(d);
          obj.parentId = value;
          if(!obj.children || obj.children.length === 0){
            obj.children = null;
          }else{
            obj.children = this.initChildren(obj.children,obj.value);
          }
          return obj
        })
      },
      // 获取表格数据
      getTableData() {
        let param = {
          pageNumber: this.pageNumber,
          pageSize: this.pageSize,
          filter: this.searchFilter
        };
        let url = this.isEmpty(this.orgId) ? this.urls.getTableDataUrl : `${this.urls.getTableDataUrl}?orgId=${this.orgId}`;
        this.httpRequest("post", url, param, {
          fullSuccess: true
        }).then(res => {
          if(res.value && res.value.data){
            this.tableData = res.value.data.map(d => {
              let obj = this.cloneObj(d);
              obj.id = d.user_id;
              return obj;
            })
            this.totalRecords = res.value.rows;
          }else{
            this.tableData = [];
            this.totalRecords = 0;
          }
        })
      },
      // 显示弹框，新增、编辑、删除、重置密码等操作时显示
      showModal(str, data) {
        this.currentRow = data;
        if (str === "add") {
          this.dialogTitle = "新增";
          this.dialogItems = this.getModalDefaultInfo(this.cols, 'addable',this);
          this.dialogVisible = true;
          this.showSaveButton = true;
        } else if (str === "edit") {
          this.dialogTitle = "编辑";
          this.showSaveButton = true;
          let info = this.cloneObj(this.getModalDefaultInfo(this.cols,"editable",this));
          this.dialogItems = info.map(d => {
            let obj = this.cloneObj(d);
            if(d.type === 'multiSelect' || d.type === 'selectCascader'){
              let value = this.currentRow[d.field] ? this.currentRow[d.field] : [];
              //组织机构回填
              if(value.length > 0 && d.field === "user_org_edit"){
                value = this.selectOrgTree(this.orgItems,value[0],[]).reverse();
              }
              obj["value"] = value;
            }else{
              if(d.field === "user_status"){
                d.option.forEach(o => {
                  o.label === this.currentRow[d.field] && (obj["value"] = o.value);
                })
              }else{
                obj["value"] = this.currentRow[d.field];
              }
            }
            return obj;
          });
          this.dialogVisible = true;
        } else if (str === "delete") {
          if (this.selectedData.length <= 0) {
            this.$message.warning("请至少选择一项进行删除！");
            return;
          }
          this.dialogTitle = "删除";
          this.dialogVisible = true;
          this.showSaveButton = false;
        } else if (str === "resetPwd") {
          this.dialogTitle = "重置密码";
          this.dialogVisible = true;
          this.showSaveButton = false;
        } else if (str === 'editPwd') {
          this.dialogTitle = "修改密码";
          this.editPwdItems.forEach(d =>{
            d.value = "";
          });
          this.dialogVisible = true;
          this.showSaveButton = false;
        }
      },
      //选中组织机构
      selectOrgTree (arr, value,temp) {
        for (let i = 0; i < arr.length; i++) {
          let item = arr[i];
          if (item.value === value) {
            temp.push(item.value);
            this.selectOrgTree(this.orgItems, item.parentId,temp);
            break;
          } else {
            if(value){
              if (item.children) {
                this.selectOrgTree(item.children, value,temp)
              }
            }else{
              break;
            }
          }
        }
        return temp
      },
      // 新增/编辑 保存
      save(title) {
        let param = this.saveVerification(this.dialogItems,this);
        if(!param){return;}
        // console.log("param",param);
        param.user_org_edit && param.user_org_edit.length > 0 && (param["user_org_edit"] = [param.user_org_edit.pop()]);
        if(title === "编辑"){
          param["user_id"] = this.currentRow["user_id"];
          this.saveData('put',param);
        }else{
          this.saveData('post',param);
          /*this.orgId = "";
          this.highlightCurrent = false;*/
        }
      },
      saveData(type,param) {
        this.httpRequest(type, this.urls.addUrl, param, {
          fullSuccess: true
        }).then(res => {
          this.message(this, "success", res.message);
          this.dialogVisible = false;
          this.getTableData();
        })
      },
      confirm(title) {
        if (title === "删除") {
          this.deleteData();
        } else if (title === "重置密码") {
          this.resetPwd();
        } else if (title === '修改密码') {
          this.editPasswords();
        }
      },
      //  删除数据
      deleteData() {
        let me = this;
        me.clearSelect = false;
        let ids = this.selectedData.map(d => {
          return d.id;
        });
        this.httpRequest("post", this.urls.deleteUrl, ids, {
          fullSuccess: true
        }).then(res => {
          me.message(me, "success", res.message);
          me.dialogVisible = false;
          me.pageNumber = 1;
          /*me.orgId = "";
          me.highlightCurrent = false;*/
          me.getTableData();
          me.clearSelect = true;
        }).catch(err => {
          //me.message(me, "error", err.message);
          me.dialogVisible = false;
        })
      },
      //修改密码
      editPasswords() {
        let param = this.saveVerification(this.editPwdItems,this);
        this.httpRequest("put", `${this.urls.editPwdUrl}/${this.currentRow.user_id}`, param, {
          fullSuccess: true
        }).then(res => {
          this.message(this, "success", res.message);
          this.dialogVisible = false;
          this.getTableData();
        }).catch(err => {
          // this.dialogVisible = false;
        })
      },
      // 表格选中项发生改变时，触发的函数
      selectChange(selection) {
        this.selectedData = selection;
      },
      // pageSize更改时，触发的回调
      sizeChange(size) {
        this.pageNumber = 1;
        this.pageSize = size;
        this.getTableData();
      },
      // 上一页、下一页等改变pageNumber时的回调
      pageChange(page) {
        this.pageNumber = page;
        this.getTableData();
      },
      // 重置密码
      resetPwd() {
        let me = this;
        this.httpRequest("put", this.urls.resetPwdUrl + "?userid=" + me.currentRow.id, {}, {
          fullSuccess: true,
        }).then(res => {
          me.message(me, "success", res.message);
          me.dialogVisible = false;
        }).catch(err => {
          me.message(me, "error", err.message);
          me.dialogVisible = false;
        })
      },
      clickOperate(e) {
        switch (e.btnText) {
          case '编辑':
            this.showModal('edit', e.row)
            break;
          case '重置密码':
            this.showModal('resetPwd', e.row)
            break;
          case '修改密码':
            this.showModal('editPwd', e.row)
            break;
          default:
            break;
        }
      },
      // 查询
      search(e) {
        let param = {filter: {}};
        e.forEach(d => {
          if (!this.isEmpty(d.value)) {
            if (d.type == "daterange") {
              param.filter[d.field] = [this.timeFormatInit(d.value[0]),this.timeFormatInit(d.value[1])];
            } else {
              param.filter[d.field] = [d.value];
            }
          }
        })
        this.pageNumber = 1;
        this.searchFilter = param.filter;
        this.getTableData();
      },
      //点击树节点筛选用户
      treeClick(e){
        this.orgId = e.data.id;
        this.getTableData();
      }
    }
  }
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
  @import "../../../assets/styles/base_style";
  .user-manage-wrapper {
    width: 100%;
    height: 100%;
    .user-row{
      height: 100%;
      .user-col{
        height: 100%;
        overflow-y: auto;
        @include scrollbarStyle(6px,6px,transparent,#DDE5F0);
      }
    }
    .operate-button-group {
      margin-bottom: 10px;
    }
    .box-card{
      height: 100%;
    }
  }
</style>
<style lang="scss" rel="stylesheet/scss">
  @import "../../../assets/styles/base_style";
  .user-manage-wrapper {
    .el-card__body {
      height: calc(100% - 50px);
      padding: 0 5px 0 0;
    }
    .el-card__header {
      background: #EFF3FE;
      border: 1px solid #e1e1e1;
      height: 42px;
      padding: 10px 15px;
      position: relative;
    }
  }
</style>
